// 区域变量
var errmsg = "";
var errfld = null;

// 现场检查
function check_field(fld, msg)
{
    if ((fld.value = fld.value.trim()) == "")
        error_field(fld, msg);
    else
        clear_field(fld);
}

// 字段错误显示
function error_field(fld, msg)
{
    if (msg != "")
        errmsg += msg + "\n";
    if (!errfld) errfld = fld;
    fld.style.background = "#BDDEF7";
}

// 清理现场
function clear_field(fld)
{
    fld.style.background = "#FFFFFF";
}


// 在数字上 , 输出逗号
function number_format(data)
{

    var tmp = '';
    var number = '';
    var cutlen = 3;
    var comma = ',';
    var i;
    
    data = data + '';

    var sign = data.match(/^[\+\-]/);
    if(sign) {
        data = data.replace(/^[\+\-]/, "");
    }

    len = data.length;
    mod = (len % cutlen);
    k = cutlen - mod;
    for (i=0; i<data.length; i++)
    {
        number = number + data.charAt(i);

        if (i < data.length - 1)
        {
            k++;
            if ((k % cutlen) == 0)
            {
                number = number + comma;
                k = 0;
            }
        }
    }

    if(sign != null)
        number = sign+number;

    return number;
}

// 新窗口
function popup_window(url, winname, opt)
{
    window.open(url, winname, opt);
}


// “泡沫邮件” 窗口
function popup_formmail(url)
{
    opt = 'scrollbars=yes,width=417,height=385,top=10,left=20';
    popup_window(url, "wformmail", opt);
}

// , 摆脱.
function no_comma(data)
{
    var tmp = '';
    var comma = ',';
    var i;

    for (i=0; i<data.length; i++)
    {
        if (data.charAt(i) != comma)
            tmp += data.charAt(i);
    }
    return tmp;
}

// 检查是否删除
function del(href)
{
    if(confirm("有没有办法恢复一次删除的材料.\n\n你真的要删除吗?")) {

        var token = generate_token();

        if (href.indexOf("?") > -1) {
            href += "&token=" + token;
        } else {
            href += "?token=" + token;
        }

        document.location.href = href;
    }
}

// Cookie输入
function set_cookie(name, value, expirehours, domain)
{
    var today = new Date();
    today.setTime(today.getTime() + (60*60*1000*expirehours));
    document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + today.toGMTString() + ";";
    if (domain) {
        document.cookie += "domain=" + domain + ";";
    }
}

// 获取Cookie
function get_cookie(name)
{
	var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
	if (match) return unescape(match[2]);
	return "";
}

// cookie保存
function delete_cookie(name)
{
    var today = new Date();

    today.setTime(today.getTime() - 1);
    var value = get_cookie(name);
    if(value != "")
        document.cookie = name + "=" + value + "; path=/; expires=" + today.toGMTString();
}

var last_id = null;
function menu(id)
{
    if (id != last_id)
    {
        if (last_id != null)
            document.getElementById(last_id).style.display = "none";
        document.getElementById(id).style.display = "block";
        last_id = id;
    }
    else
    {
        document.getElementById(id).style.display = "none";
        last_id = null;
    }
}

function textarea_decrease(id, row)
{
    if (document.getElementById(id).rows - row > 0)
        document.getElementById(id).rows -= row;
}

function textarea_original(id, row)
{
    document.getElementById(id).rows = row;
}

function textarea_increase(id, row)
{
    document.getElementById(id).rows += row;
}

// 书写编号检查
function check_byte(content, target)
{
    var i = 0;
    var cnt = 0;
    var ch = '';
    var cont = document.getElementById(content).value;

    for (i=0; i<cont.length; i++) {
        ch = cont.charAt(i);
        if (escape(ch).length > 4) {
            cnt += 2;
        } else {
            cnt += 1;
        }
    }
    // 输出编号
    document.getElementById(target).innerHTML = cnt;

    return cnt;
}

// 浏览器中对象左侧的坐标
function get_left_pos(obj)
{
    var parentObj = null;
    var clientObj = obj;
    //var left = obj.offsetLeft + document.body.clientLeft;
    var left = obj.offsetLeft;

    while((parentObj=clientObj.offsetParent) != null)
    {
        left = left + parentObj.offsetLeft;
        clientObj = parentObj;
    }

    return left;
}

// 对象在浏览器中的顶部坐标
function get_top_pos(obj)
{
    var parentObj = null;
    var clientObj = obj;
    //var top = obj.offsetTop + document.body.clientTop;
    var top = obj.offsetTop;

    while((parentObj=clientObj.offsetParent) != null)
    {
        top = top + parentObj.offsetTop;
        clientObj = parentObj;
    }

    return top;
}

function obj_movie(src, ids, width, height, autostart)
{
    var wh = "";
    if (parseInt(width) && parseInt(height))
        wh = " width='"+width+"' height='"+height+"' ";
    if (!autostart) autostart = false;
    return "<embed src='"+src+"' "+wh+" autostart='"+autostart+"'></embed>";
}

var win_password_lost = function(href) {
    window.open(href, "win_password_lost", "left=50, top=50, width=617, height=330, scrollbars=1");
}

$(document).ready(function(){
    $("#login_password_lost, #ol_password_lost").click(function(){
        win_password_lost(this.href);
        return false;
    });
});

/**
 * 点窗口
 **/
var win_point = function(href) {
    var new_win = window.open(href, 'win_point', 'left=100,top=100,width=600, height=600, scrollbars=1');
    new_win.focus();
}

/**
 * “备注” 窗口
 **/
var win_memo = function(href) {
    var new_win = window.open(href, 'win_memo', 'left=100,top=100,width=620,height=500,scrollbars=1');
    new_win.focus();
}

/**
 * “备注” 窗口
 **/
var check_goto_new = function(href, event) {
    if( !(typeof g6_is_mobile != "undefined" && g6_is_mobile) ){
        if (window.opener && window.opener.document && window.opener.document.getElementById) {
            event.preventDefault ? event.preventDefault() : (event.returnValue = false);
            window.open(href);
            //window.opener.document.location.href = href;
        }
    }
}

/**
 * “邮件” 窗口
 **/
var win_email = function(href) {
    var new_win = window.open(href, 'win_email', 'left=100,top=100,width=600,height=580,scrollbars=1');
    new_win.focus();
}

/**
 * 自我介绍窗口
 **/
var win_profile = function(href) {
    var new_win = window.open(href, 'win_profile', 'left=100,top=100,width=620,height=510,scrollbars=1');
    new_win.focus();
}

/**
 * “废料” 窗口
 **/
var win_scrap = function(href) {
    var new_win = window.open(href, 'win_scrap', 'left=100,top=100,width=600,height=600,scrollbars=1');
    new_win.focus();
}

/**
 * 主页窗口
 **/
var win_homepage = function(href) {
    var new_win = window.open(href, 'win_homepage', '');
    new_win.focus();
}

/**
 * 邮政号码窗口
 **/
var win_zip = function(frm_name, frm_zip, frm_addr1, frm_addr2, frm_addr3, frm_jibeon) {
    if(typeof daum === "undefined"){
        alert("KAKAO 邮政服务 postcode.v2.js 该文件尚未收费.");
        return false;
    }

    // 消除双指缩放现象
    var vContent = "width=device-width,initial-scale=1.0,minimum-scale=0,maximum-scale=10";
    $("#meta_viewport").attr("content", vContent + ",user-scalable=no");

    var zip_case = 1;   //0背层, 1插入到后页, 2背面新窗口

    var complete_fn = function(data){
        // 编写代码的一部分，以便在单击弹出窗口中的搜索结果项时运行.

        // 每个地址应根据暴露规则进行组合.
        // 如果向下的变量没有值，则为空。('')因为它有一个值, 注意这一点，使四分之一.
        var fullAddr = ''; // 最终地址变量
        var extraAddr = ''; // 组合地址变量

        // 根据用户选择的地址类型导入对应的地址值.
        if (data.userSelectedType === 'R') { // 如果用户选择了道路名称地址
            fullAddr = data.roadAddress;

        } else { // 当用户选择地址时(J)
            fullAddr = data.jibunAddress;
        }

        // 当用户选择的地址是道路名称类型时，将其组合.
        if(data.userSelectedType === 'R'){
            //如果有合法名称，请添加它。.
            if(data.bname !== ''){
                extraAddr += data.bname;
            }
            // 如果有建筑物名称，请添加.
            if(data.buildingName !== ''){
                extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
            }
            // 根据组合地址在两侧添加括号，创建最终地址。.
            extraAddr = (extraAddr !== '' ? ' ('+ extraAddr +')' : '');
        }

        // 将您的邮政编码和地址信息放在相应的字段中，, 将光标移动到详细地址字段.
        var of = document[frm_name];

        of[frm_zip].value = data.zonecode;

        of[frm_addr1].value = fullAddr;
        of[frm_addr3].value = extraAddr;

        if(of[frm_jibeon] !== undefined){
            of[frm_jibeon].value = data.userSelectedType;
        }
        
        setTimeout(function(){
            $("#meta_viewport").attr("content", vContent);
            of[frm_addr2].focus();
        } , 100);
    };

    switch(zip_case) {
        case 1 :    //iframe用于将其插入页面
        case 1 :    //iframe을 이용하여 페이지에 끼워 넣기
            var daum_pape_id = 'daum_juso_page'+frm_zip,
                element_wrap = document.getElementById(daum_pape_id),
                currentScroll = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
            if (element_wrap == null) {
                element_wrap = document.createElement("div");
                element_wrap.setAttribute("id", daum_pape_id);
                element_wrap.style.cssText = 'display:none;border:1px solid;left:0;width:100%;height:300px;margin:5px 0;position:relative;';
                element_wrap.innerHTML = '<img src="//t1.daumcdn.net/postcode/resource/images/close.png" id="btnFoldWrap" style="cursor:pointer;position:absolute;right:0px;top:-21px;z-index:1" class="close_daum_juso" alt="折叠按钮">';
                jQuery('form[name="'+frm_name+'"]').find('input[name="'+frm_addr1+'"]').before(element_wrap);
                jQuery("#"+daum_pape_id).off("click", ".close_daum_juso").on("click", ".close_daum_juso", function(e){
                    e.preventDefault();
                    $("#meta_viewport").attr("content", vContent);
                    jQuery(this).parent().hide();
                });
            }

            new daum.Postcode({
                oncomplete: function(data) {
                    complete_fn(data);
                    // iframeput element我不明白.
                    element_wrap.style.display = 'none';
                    // 在您看到 “查找您的邮政号码” 屏幕之前 scroll 我们返回位置.
                    document.body.scrollTop = currentScroll;
                },
                // 找到您的邮政编码将编写代码以在调整屏幕大小时运行的部分.
                // iframeput element我们调整的高度值.
                onresize : function(size) {
                    element_wrap.style.height = size.height + "px";
                },
                maxSuggestItems : g6_is_mobile ? 6 : 10,
                width : '100%',
                height : '100%'
            }).embed(element_wrap);

            // iframeput element让你看起来.
            element_wrap.style.display = 'block';
            break;
        case 2 :    //用新窗口浮动
            new daum.Postcode({
                oncomplete: function(data) {
                    complete_fn(data);
                }
            }).open();
            break;
        default :   //iframe用于浮动图层
            var rayer_id = 'daum_juso_rayer'+frm_zip,
                element_layer = document.getElementById(rayer_id);
            if (element_layer == null) {
                element_layer = document.createElement("div");
                element_layer.setAttribute("id", rayer_id);
                element_layer.style.cssText = 'display:none;border:5px solid;position:fixed;width:300px;height:460px;left:50%;margin-left:-155px;top:50%;margin-top:-235px;overflow:hidden;z-index:10000';
                element_layer.innerHTML = '<img src="//i1.daumcdn.net/localimg/localimages/07/postcode/320/close.png" id="btnCloseLayer" style="cursor:pointer;position:absolute;right:-3px;top:-3px;z-index:1" class="close_daum_juso" alt="“关闭” 按钮">';
                document.body.appendChild(element_layer);
                jQuery("#"+rayer_id).off("click", ".close_daum_juso").on("click", ".close_daum_juso", function(e){
                    e.preventDefault();
                    $("#meta_viewport").attr("content", vContent);
                    jQuery(this).parent().hide();
                });
            }

            new daum.Postcode({
                oncomplete: function(data) {
                    complete_fn(data);
                    // iframeput element我不明白.
                    element_layer.style.display = 'none';
                },
                maxSuggestItems : g6_is_mobile ? 6 : 10,
                width : '100%',
                height : '100%'
            }).embed(element_layer);

            // iframeput element让你看起来.
            element_layer.style.display = 'block';
    }
}

/**
 * “新密码丢失” 窗口 : 101123
 **/
win_password_lost = function(href)
{
    var new_win = window.open(href, 'win_password_lost', 'width=617, height=330, scrollbars=1');
    new_win.focus();
}

/**
 * 调查结果
 **/
var win_poll = function(href) {
    var new_win = window.open(href, 'win_poll', 'width=616, height=500, scrollbars=1');
    new_win.focus();
}

/**
 * 优惠券
 **/
var win_coupon = function(href) {
    var new_win = window.open(href, "win_coupon", "left=100,top=100,width=700, height=600, scrollbars=1");
    new_win.focus();
}


/**
 * 屏幕阅读器用户的脚本 - 爸爸谁得到了它 2013-04-22
 * alt 将鼠标悬停在仅包含值的图形链接上 title 给定值, 鼠标移出 title 删除值
 **/
$(function() {
    $('a img').mouseover(function() {
        $a_img_title = $(this).attr('alt');
        $(this).attr('title', $a_img_title);
    }).mouseout(function() {
        $(this).attr('title', '');
    });
});

/**
 * 调整文本大小
**/
function font_resize(id, rmv_class, add_class, othis)
{
    var $el = $("#"+id);

	if((typeof rmv_class !== "undefined" && rmv_class) || (typeof add_class !== "undefined" && add_class)){
		$el.removeClass(rmv_class).addClass(add_class);

		set_cookie("ck_font_resize_rmv_class", rmv_class, 1, g6_cookie_domain);
		set_cookie("ck_font_resize_add_class", add_class, 1, g6_cookie_domain);
	}

    if(typeof othis !== "undefined"){
        $(othis).addClass('select').siblings().removeClass('select');
    }
}

$(function(){
    $(".win_point").click(function() {
        win_point(this.href);
        return false;
    });

    $(".win_memo").click(function() {
        win_memo(this.href);
        return false;
    });

    $(".win_email").click(function() {
        win_email(this.href);
        return false;
    });

    $(".win_scrap").click(function() {
        win_scrap(this.href);
        return false;
    });

    $(".win_profile").click(function() {
        win_profile(this.href);
        return false;
    });

    $(".win_homepage").click(function() {
        win_homepage(this.href);
        return false;
    });

    $(".win_password_lost").click(function() {
        win_password_lost(this.href);
        return false;
    });

    /*
    $(".win_poll").click(function() {
        win_poll(this.href);
        return false;
    });
    */

    $(".win_coupon").click(function() {
        win_coupon(this.href);
        return false;
    });

    // 侧视图
    var sv_hide = false;
    $(".sv_member, .sv_guest").click(function() {
        $(".sv").removeClass("sv_on");
        $(this).closest(".sv_wrap").find(".sv").addClass("sv_on");
    });

    $(".sv, .sv_wrap").hover(
        function() {
            sv_hide = false;
        },
        function() {
            sv_hide = true;
        }
    );

    $(".sv_member, .sv_guest").focusin(function() {
        sv_hide = false;
        $(".sv").removeClass("sv_on");
        $(this).closest(".sv_wrap").find(".sv").addClass("sv_on");
    });

    $(".sv a").focusin(function() {
        sv_hide = false;
    });

    $(".sv a").focusout(function() {
        sv_hide = true;
    });

    // 选择 ul
    var sel_hide = false;
    $('.sel_btn').click(function() {
        $('.sel_ul').removeClass('sel_on');
        $(this).siblings('.sel_ul').addClass('sel_on');
    });

    $(".sel_wrap").hover(
        function() {
            sel_hide = false;
        },
        function() {
            sel_hide = true;
        }
    );

    $('.sel_a').focusin(function() {
        sel_hide = false;
    });

    $('.sel_a').focusout(function() {
        sel_hide = true;
    });

    $(document).click(function() {
        if(sv_hide) { // 侧视图关闭
            $(".sv").removeClass("sv_on");
        }
        if (sel_hide) { // 选择 ul 关
            $('.sel_ul').removeClass('sel_on');
        }
    });

    $(document).focusin(function() {
        if(sv_hide) { // 侧视图关闭
            $(".sv").removeClass("sv_on");
        }
        if (sel_hide) { // 选择 ul 关
            $('.sel_ul').removeClass('sel_on');
        }
    });

    $(document).on( "keyup change", "textarea#wr_content[maxlength]", function(){
        var str = $(this).val();
        var mx = parseInt($(this).attr("maxlength"));
        if (str.length > mx) {
            $(this).val(str.substr(0, mx));
            return false;
        }
    });
});

function get_write_token(bo_table)
{
    var token = "";

    $.ajax({
        type: "POST",
        url: g6_bbs_url+"/write_token.php",
        data: { bo_table: bo_table },
        cache: false,
        async: false,
        dataType: "json",
        success: function(data) {
            if(data.error) {
                alert(data.error);
                if(data.url)
                    document.location.href = data.url;

                return false;
            }

            token = data.token;
        }
    });

    return token;
}

$(function() {
    $(document).on("click", "form[name=fwrite] input:submit, form[name=fwrite] button:submit, form[name=fwrite] input:image", function() {
        // var f = this.form;

        // if (typeof(f.bo_table) == "undefined") {
        //     return;
        // }

        // var bo_table = f.bo_table.value;
        // var token = get_write_token(bo_table);

        // if(!token) {
        //     alert("令牌信息不正确.");
        //     return false;
        // }

        // var $f = $(f);

        // if(typeof f.token === "undefined")
        //     $f.prepend('<input type="hidden" name="token" value="">');

        // $f.find("input[name=token]").val(token);

        return true;
    });

    // 当服务器返回错误时 `btn_submit` 重新激活按钮
    // - alert窗口后 history.back()
    window.onpageshow = function(event){
        if(event.persisted || (window.performance && performance.getEntriesByType("navigation")[0].type === 'back_forward')) {
            const $btn_submit = document.getElementById("btn_submit")
            if ($btn_submit) {
                $btn_submit.disabled = false;
            }
        }
    }
});


function generate_token() {
    var token = "";
    $.ajax({
        url: '/generate_token',
        type: 'POST',
        async: false,
        cache: false,
        success: function(response) {
            if (response.success) {
                token = response.token;
            } else {
                alert("创建令牌失败.");
                token = '';
            }
        },
        error: function(xhr, status, error) {
            console.log(error);
        }
    });
    return token;
}

// 设置dink模式
// 屏幕模式切换按钮的event-runner功能
document.addEventListener('DOMContentLoaded', function () {
  const darkmodeBtn = document.querySelector('#darkmode-toggle-switch');
  darkmodeBtn?.addEventListener('click', handleDarkMode);
  isDarkModeEnabled(darkmodeBtn);
});

// Dark mode 切换按钮单击事件
function handleDarkMode(e) {
    const currentTheme = e.currentTarget.classList.contains('dark') ? 'light' : 'dark';
    e.currentTarget.classList.toggle('dark');
    localStorage.setItem('color-theme', currentTheme);
    document.documentElement.setAttribute('color-theme', currentTheme);
}

// Dark mode 状态检查功能
function isDarkModeEnabled(btn) {
    const isUserColorTheme = localStorage.getItem('color-theme');
    const isOsColorTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    const getUserTheme = () => (isUserColorTheme ? isUserColorTheme : isOsColorTheme);
    const initialTheme = getUserTheme();
    if (initialTheme === 'dark') {
        btn.classList.add('dark');
        document.documentElement.setAttribute('color-theme', 'dark');
    } else {
        document.documentElement.setAttribute('color-theme', 'light');
    }
}

// 基于本地存储数据的实时更改
window.addEventListener('storage', isDarkModeEnabled);
